﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RestSharp;
using Newtonsoft.Json.Linq;

namespace Tradier
{
    public partial class Logins : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Session["UserTradierAccessToken"] = "xmBiyo2TuyqzE3LIBiB8vxKSf2xR";
            //if (!string.IsNullOrEmpty(Request.QueryString["code"]))
            //{
            //    ObtainUsersAccessToken(Request.QueryString["code"]);
            //}
        }

        protected void OnLoginButtonClicked(object sender, EventArgs e)
        {
            Response.Redirect(string.Format("https://api.tradier.com/v1/oauth/authorize?client_id={0}&scope={1}&state={2}", Tradier.TradierConfiguration.ConsumerKey, Tradier.TradierConfiguration.Scopes, TradierConfiguration.State));
        }

        private void ObtainUsersAccessToken(string code)
        {
            try
            {
                var client = new RestClient("https://api.tradier.com");
                var request = new RestRequest("/v1/oauth/accesstoken", Method.POST);

                var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(string.Format("{0}:{1}", TradierConfiguration.ConsumerKey, TradierConfiguration.ConsumerSecret));
                var authorization = Convert.ToBase64String(plainTextBytes);

                request.AddHeader("Content-type", "application/x-www-form-urlencoded");
                request.AddHeader("Authorization", authorization);

                request.AddParameter("code", code);
                request.AddParameter("grant_type", "authorization_code");

                var result = (client.Execute(request).Content);
                var json = JObject.Parse(result);

                var accessToken = (string)json["access_token"];
                Session["UserTradierAccessToken"] = accessToken;

                Response.Redirect("user.aspx");
            }
            catch
            {

            }
        }
    }
}